package com.pactera.madp.cp.controller.oms.remind;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.pactera.madp.common.core.exception.CheckedException;
import com.pactera.madp.common.core.util.R;
import com.pactera.madp.common.log.annotation.SysLog;
import com.pactera.madp.common.security.annotation.Inner;
import com.pactera.madp.cp.api.bo.IndexMsgBO;
import com.pactera.madp.cp.api.constant.DeptConstants;
import com.pactera.madp.cp.api.dto.contact.MsgToEmployeeDTO;
import com.pactera.madp.cp.api.dto.contactLoss.ContactLossDetailsTendencyDTO;
import com.pactera.madp.cp.api.dto.contactLoss.ContactNoCommunicationTendencyDTO;
import com.pactera.madp.cp.api.dto.contactLoss.LossDto;
import com.pactera.madp.cp.api.dto.msg.MsgVo;
import com.pactera.madp.cp.api.entity.BaseEntity;
import com.pactera.madp.cp.api.entity.WorkDeptEntity;
import com.pactera.madp.cp.api.entity.clientLossManagement.RemindCommunicationEntity;
import com.pactera.madp.cp.api.feign.RemoteDeptService;
import com.pactera.madp.cp.api.page.SubPage;
import com.pactera.madp.cp.api.vo.contact.ContactEmployeeTagVO;
import com.pactera.madp.cp.api.vo.contactloss.*;
import com.pactera.madp.cp.handler.CorpContextHolder;
import com.pactera.madp.cp.service.IContactLossService;
import com.pactera.madp.cp.service.IContactService;
import com.pactera.madp.cp.service.IWorkDeptService;
import com.pactera.madp.cp.service.RemindCommunicationService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

@RestController
@AllArgsConstructor
@RequestMapping("/contactloss")
@Api(value = "ContactLoss", tags = "客户流失管理")
public class ContactLossController {

    @Autowired
    private IContactLossService contactLossService;
    @Resource
    private IContactService contactService;
    @Autowired
    private RemoteDeptService remoteDeptService;
    @Autowired
    private IWorkDeptService workDeptService;
    @Autowired
    private RemindCommunicationService remindCommunicationService;

    @GetMapping("/obj-list/{deptId}")
    @ApiOperation("根据deptId获取objectList(下一级机构list/当前机构下成员list)")
    public R<ObjListVO> getObjListByDeptId(@PathVariable("deptId") Integer deptId) {
        return R.ok(contactLossService.getObjListByDeptId(deptId));
    }

    @GetMapping("/loss-statistics/{deptId}")
    @ApiOperation(value = "华融湘江-客户流失基础信息统计")
    public R<ContactLossPageVo> getLossStatisticsData(@PathVariable("deptId")Integer deptId) {
        R r = remoteDeptService.getWxDeptId(deptId);
        Integer wxDeptId = (Integer) r.getData();
        ContactLossPageVo entity = contactLossService.getLossStatisticsDatas(deptId, wxDeptId);
        return R.ok(entity);
    }

    @GetMapping("/loss-statistics-page/{deptId}")
    @ApiOperation(value = "华融湘江-客户流失统计分页查询")
    @ApiImplicitParams({
            @ApiImplicitParam(name="deptId",value="当前机构id",dataType ="Integer"),
            @ApiImplicitParam(name="objectId",value="子级机构id/成员id",dataType ="Integer")
    })
    public R<IPage<ContactLossPageVo>> getLossStatisticsDataPage(@PathVariable("deptId")Integer deptId,
                                                      @RequestParam(name = "objectId",required = false) Integer objectId,
                                                      Page page) {
        R r = remoteDeptService.getWxDeptId(deptId);
        Integer wxDeptId = (Integer) r.getData();
        WorkDeptEntity workDeptEntity = workDeptService.getOne(
                Wrappers.<WorkDeptEntity>lambdaQuery()
                        .select(WorkDeptEntity::getLevel)
                        .eq(WorkDeptEntity::getWxDepartmentId, wxDeptId)
        );
        Integer level = workDeptEntity.getLevel();
        if (level < DeptConstants.SUB_BRANCH_LEVEL) {
            LinkedHashMap pageResult = (LinkedHashMap) remoteDeptService.getChildrenPage(deptId, page).getData();
            if (objectId != null) {
                pageResult = (LinkedHashMap) remoteDeptService.getChildrenPageByObjectId(deptId, page,objectId).getData();
            }
            Page<ContactLossPageVo> vos = JSON.parseObject(JSON.toJSONString(pageResult), new TypeReference<Page<ContactLossPageVo>>() {});
            vos.getRecords().forEach(s -> {
                ContactLossPageVo entity1 = contactLossService.getLossStatisticsDatas(s.getId(), Integer.parseInt(s.getCode()));
                s.setContactTotalCount(entity1.getContactTotalCount());
                s.setContactLossTotalCount(entity1.getContactLossTotalCount());
                s.setWxLossCount(entity1.getWxLossCount());
                s.setQywxLossCount(entity1.getQywxLossCount());
                s.setYesterdayNetGrowthCount(entity1.getYesterdayNetGrowthCount());
                s.setYesterdayLossCount(entity1.getYesterdayLossCount());
                s.setYesterdayAddedCount(entity1.getYesterdayAddedCount());
                s.setCode(s.getName());
                s.setName(entity1.getName());
            });
            SubPage subPage = new SubPage();
            HashMap<String, Object> map = new HashMap<>();
            map.put("pageObjectType","dept");
            subPage.setExtraProps(map);
            subPage.setRecords(vos.getRecords());
            subPage.setSize(vos.getSize());
            subPage.setCurrent(vos.getCurrent());
            subPage.setTotal(vos.getTotal());
            subPage.setPages(vos.getPages());
            return R.ok(subPage);
        } else {
            LinkedHashMap pageResult = (LinkedHashMap) remoteDeptService.getUserPage(null, deptId, page).getData();
            if (objectId != null) {
                pageResult = (LinkedHashMap) remoteDeptService.getUserPageByObjectId(null,deptId,page,objectId).getData();
            }
            Page<ContactLossPageVo> vos = JSON.parseObject(JSON.toJSONString(pageResult), new TypeReference<Page<ContactLossPageVo>>() {});
            vos.getRecords().forEach(s -> {
                ContactLossPageVo entity1 = contactLossService.getLossStatisticsDatas(s.getCode());
                s.setContactTotalCount(entity1.getContactTotalCount());
                s.setContactLossTotalCount(entity1.getContactLossTotalCount());
                s.setWxLossCount(entity1.getWxLossCount());
                s.setQywxLossCount(entity1.getQywxLossCount());
                s.setYesterdayNetGrowthCount(entity1.getYesterdayNetGrowthCount());
                s.setYesterdayLossCount(entity1.getYesterdayLossCount());
                s.setYesterdayAddedCount(entity1.getYesterdayAddedCount());
                s.setCode(entity1.getCode());
                s.setName(entity1.getName());
                s.setEmployeeId(entity1.getEmployeeId());
            });
            SubPage subPage = new SubPage();
            HashMap<String, Object> map = new HashMap<>();
            map.put("pageObjectType","employee");
            subPage.setExtraProps(map);
            subPage.setRecords(vos.getRecords());
            subPage.setSize(vos.getSize());
            subPage.setCurrent(vos.getCurrent());
            subPage.setTotal(vos.getTotal());
            subPage.setPages(vos.getPages());
            return R.ok(subPage);
        }
    }

    @GetMapping("/loss-tendency")
    @ApiOperation(value = "华融湘江-客户流失趋势图")
    public R<List<ContactLossStaticsTendencyVO>> lossTendency(ContactLossDetailsTendencyDTO dto) {
        Integer type = dto.getType();
        switch (type) {
            case 1:
                return R.ok(contactLossService.getContactLossTotalCount(dto));
            case 2:
                return R.ok(contactLossService.getWxLossCount(dto));
            case 3:
                return R.ok(contactLossService.getQywxLossCount(dto));
        }
        return R.failed("查询字段类型不在1-3内");
    }

    @GetMapping("/nocommunication-statistics/{deptId}")
    @ApiOperation(value = "华融湘江-客户未交流基础信息统计")
    public R<ContactNoCommunicationPageVo> getNoCommunicationStatisticsData(@PathVariable("deptId")Integer deptId) {
        R r = remoteDeptService.getWxDeptId(deptId);
        Integer wxDeptId = (Integer) r.getData();
        RemindCommunicationEntity communicationEntity = remindCommunicationService.getOne(Wrappers.<RemindCommunicationEntity>lambdaQuery().eq(RemindCommunicationEntity::getCorpId, CorpContextHolder.getCorpId()).orderByDesc(BaseEntity::getCreateTime).last("limit 1"));
        //未交流客户配置
        if(null==communicationEntity){
            return R.failed("未交流提醒已关闭");
        }
        ContactNoCommunicationPageVo entity = contactLossService.getNoCommunicationStatisticsDatas(deptId, wxDeptId,communicationEntity);
        return R.ok(entity);
    }

    @GetMapping("/nocommunication-statistics-page/{deptId}")
    @ApiOperation(value = "华融湘江-客户未交流统计分页查询")
    public R<IPage<ContactNoCommunicationPageVo>> getNoCommunicationStatisticsDataPage(@PathVariable("deptId")Integer deptId,
                                                                                @RequestParam(name = "objectId",required = false) Integer objectId,
                                                                                Page page) {
        R r = remoteDeptService.getWxDeptId(deptId);
        Integer wxDeptId = (Integer) r.getData();
        WorkDeptEntity workDeptEntity = workDeptService.getOne(
                Wrappers.<WorkDeptEntity>lambdaQuery()
                        .select(WorkDeptEntity::getLevel)
                        .eq(WorkDeptEntity::getWxDepartmentId, wxDeptId)
        );
        RemindCommunicationEntity communicationEntity = remindCommunicationService.getOne(Wrappers.<RemindCommunicationEntity>lambdaQuery().eq(RemindCommunicationEntity::getCorpId, CorpContextHolder.getCorpId()).orderByDesc(BaseEntity::getCreateTime).last("limit 1"));
        //未交流客户配置
        if(null==communicationEntity){
            return R.failed("未交流提醒已关闭");
        }
        Integer level = workDeptEntity.getLevel();
        if (level < DeptConstants.SUB_BRANCH_LEVEL) {
            LinkedHashMap pageResult = (LinkedHashMap) remoteDeptService.getChildrenPage(deptId, page).getData();
            if (objectId != null) {
                pageResult = (LinkedHashMap) remoteDeptService.getChildrenPageByObjectId(deptId, page,objectId).getData();
            }
            Page<ContactNoCommunicationPageVo> vos = JSON.parseObject(JSON.toJSONString(pageResult), new TypeReference<Page<ContactNoCommunicationPageVo>>() {});
            vos.getRecords().forEach(s -> {
                ContactNoCommunicationPageVo entity1 = contactLossService.getNoCommunicationStatisticsDatas(s.getId(), Integer.parseInt(s.getCode()),communicationEntity);
                s.setContactTotalCount(entity1.getContactTotalCount());
                s.setContactNoCommunicationTotalCount(entity1.getContactNoCommunicationTotalCount());
                s.setYesterdayAddedNoCommunicationCount(entity1.getYesterdayAddedNoCommunicationCount());
                s.setWxNoCommunicationCount(entity1.getWxNoCommunicationCount());
                s.setQywxNoCommunicationCount(entity1.getQywxNoCommunicationCount());
                s.setCode(s.getName());
                s.setName(entity1.getName());
            });
            SubPage subPage = new SubPage();
            HashMap<String, Object> map = new HashMap<>();
            map.put("pageObjectType","dept");
            subPage.setExtraProps(map);
            subPage.setRecords(vos.getRecords());
            subPage.setSize(vos.getSize());
            subPage.setCurrent(vos.getCurrent());
            subPage.setTotal(vos.getTotal());
            subPage.setPages(vos.getPages());
            return R.ok(subPage);
        } else {
            LinkedHashMap pageResult = (LinkedHashMap) remoteDeptService.getUserPage(null, deptId, page).getData();
            if (objectId != null) {
                pageResult = (LinkedHashMap) remoteDeptService.getUserPageByObjectId(null,deptId,page,objectId).getData();
            }
            Page<ContactNoCommunicationPageVo> vos = JSON.parseObject(JSON.toJSONString(pageResult), new TypeReference<Page<ContactNoCommunicationPageVo>>() {});
            vos.getRecords().forEach(s -> {
                ContactNoCommunicationPageVo entity1 = contactLossService.getNoCommunicationStatisticsDatas(s.getCode(),communicationEntity);
                s.setContactTotalCount(entity1.getContactTotalCount());
                s.setContactTotalCount(entity1.getContactTotalCount());
                s.setContactNoCommunicationTotalCount(entity1.getContactNoCommunicationTotalCount());
                s.setYesterdayAddedNoCommunicationCount(entity1.getYesterdayAddedNoCommunicationCount());
                s.setWxNoCommunicationCount(entity1.getWxNoCommunicationCount());
                s.setQywxNoCommunicationCount(entity1.getQywxNoCommunicationCount());
                s.setCode(entity1.getCode());
                s.setName(entity1.getName());
                s.setEmployeeId(entity1.getEmployeeId());
            });
            SubPage subPage = new SubPage();
            HashMap<String, Object> map = new HashMap<>();
            map.put("pageObjectType","employee");
            subPage.setExtraProps(map);
            subPage.setRecords(vos.getRecords());
            subPage.setSize(vos.getSize());
            subPage.setCurrent(vos.getCurrent());
            subPage.setTotal(vos.getTotal());
            subPage.setPages(vos.getPages());
            return R.ok(subPage);
        }
    }

    @GetMapping("/nocommunication-tendency")
    @ApiOperation(value = "华融湘江-未交流客户趋势图")
    public R<List<ContactNoCommunicationStaticsTendencyVO>> noCommunicationTendency(ContactNoCommunicationTendencyDTO dto) {
        RemindCommunicationEntity communicationEntity = remindCommunicationService.getOne(Wrappers.<RemindCommunicationEntity>lambdaQuery().eq(RemindCommunicationEntity::getCorpId, CorpContextHolder.getCorpId()).orderByDesc(BaseEntity::getCreateTime).last("limit 1"));
        //未交流客户配置
        if(null==communicationEntity){
            return R.failed("未交流提醒已关闭");
        }
        Integer type = dto.getType();
        switch (type) {
            case 1:
                return R.ok(contactLossService.getContactNoCommunicationTotalCount(dto,communicationEntity));
            case 2:
                return R.ok(contactLossService.getWxNoCommunicationCount(dto,communicationEntity));
            case 3:
                return R.ok(contactLossService.getQywxNoCommunicationCount(dto,communicationEntity));
        }
        return R.failed("查询字段类型不在1-3内");
    }

    @GetMapping("/query")
    @ApiOperation(value = "流失客户查询")
    public R query(Page page, Integer employeeId) {
        Page ipage = contactLossService.queryByDto(page, employeeId);
        return R.ok(ipage);
    }

    @GetMapping("/lossdetail")
    @ApiOperation(value = "流失客户聊天记录查询")
    public R lossDetail(Page page, LossDto dto) {
        List<MsgVo> vos = contactLossService.lossDetail(page, dto);
        return R.ok(vos);
    }
    @GetMapping("/page")
    @ApiOperation(value = "未交流客户")
    public R<IPage<ContactEmployeeTagVO>> getContactListByUser(Page page, Integer employeeId){
        return R.ok(contactService.getContactListByUser(page,employeeId));
    }

    @PostMapping("/choose")
    @ApiOperation(value = "成员的未提醒客户")
    public R getUserToContact(@RequestBody MsgToEmployeeDTO dto){
        contactService.getUserToContact(dto);
        return R.ok();
    }

    @SysLog("给成员发提醒消息-客户流失")
    @PostMapping("/msg")
    @ApiOperation(value = "给成员发提醒消息")
    public R getMsgToUser(@RequestBody MsgToEmployeeDTO dto){
        contactService.getMsgToUser(dto);
        return  R.ok();
    }

    @GetMapping("/user")
    @ApiOperation(value = "查看聊天记录")
    public R<IPage<List<IndexMsgBO>>> userMsg(@RequestParam(value = "contactId")Integer contactId, @RequestParam(value = "employeeId")Integer employeeId,Integer time,Integer type, Page page){
        return R.ok(contactService.getUserMsg(contactId, employeeId,time,type,page));
    }

    @GetMapping("count")
    @ApiOperation(value = "客户未交流客户数")
    public R<Map<String,Integer>> userMsg(@RequestParam(value = "wxUserId")String wxUserId){
        return R.ok(contactService.getUserCount(wxUserId));
    }

}
